package com.xinzhi.savingpot.service.impl;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;


@Component
@ServerEndpoint("/websocket")
public class WebSocket {
    //用来记录当前在线人数
    private static int count = 0 ;
    //用于存放每个websocket客户端对应的信息
    private static CopyOnWriteArraySet<WebSocket> websocketSet= new CopyOnWriteArraySet<WebSocket>();
    //创建会话对象通过他来给客户端发送数据
    private Session session;



    @OnOpen
    public void onopen(Session session){
        this.session = session;
        websocketSet.add(this); //将每个客户端的对象存放进去
        addCount();

        System.out.println("有新连接加入！当前在线人数"+getCount());
    }
    @OnClose
    public void onclose(Session session) {
        websocketSet.remove(this);
        leaveCount();
        System.out.println("有连接离开！当前在线人数"+getCount());
    }


    @OnMessage
    public void onSend(String msg){

        System.out.println("来自客户端的消息"+msg);

        //群发消息
        for (WebSocket so: websocketSet) {
            try {
                so.sendMessage(msg);
            } catch (IOException e) {
                e.printStackTrace();
                continue;
            }
        }


    }

    @OnError
    public void onError(Session session, Throwable error){
        System.out.println("发生错误");
        error.printStackTrace();
    }



    public void sendMessage(String message) throws IOException{

        this.session.getBasicRemote().sendText(message);
        //this.session.getAsyncRemote().sendText(message);
    }

    //当有用户加进来数量叠加
    public static synchronized  void addCount(){
      WebSocket.count++; }
    //用户离开
    public static synchronized  void leaveCount(){
        WebSocket.count--; }
    //返回用户在线人数
    public static synchronized int getCount(){return count; }

}
